package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.mapper.RecordCourseMapper;
import com.xmy.cultivate.mapper.StudentLeaveApplyMapper;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.respons.LeaveApply;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 学生请假申请表 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-11-10
 */
@Service
public class StudentLeaveApplyServiceImpl extends ServiceImpl<StudentLeaveApplyMapper, StudentLeaveApply> implements IStudentLeaveApplyService {

    @Autowired
    StudentLeaveApplyMapper studentLeaveApplyMapper;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IdWorker idWorker;


    @Override
    public List<LeaveApply> getNotHandleLeaveList(Long adminId) {
        return studentLeaveApplyMapper.getNotHandleLeaveList(adminId);
    }

    @Override
    public List<LeaveApply> getHandleLeaveList(Long adminId) {
        return studentLeaveApplyMapper.getHandleLeaveList(adminId);
    }

    /**
     * 正常排课的添加请假（没有到课的数据）
     */
    @Override
    public RecordCourse addLeaveData(Long schedulingDetailId, Long studentId, Integer buckleHouse, StatusRecordEnum status, Integer type, Integer courseType, Quarter quarterNow) {
        try {
            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.last("limit 1");
            RecordCourse recordCourse = recordCourseMapper.selectOne(queryWrapper);
            //已经添加过的，直接返回
            if (recordCourse != null) {
                return recordCourse;
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return null;
            }

            Grade grade = null;
            Grade oldGrade = new Grade();
            if (courseSchedulingDetailInfo.getGradeId() != null) {
                grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            }
            if (grade == null) {
                grade = new Grade();
            }

            //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
            StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, 1);
            if (studentGrade != null) {
                oldGrade = iGradeService.getById(studentGrade.getGradeId());
                if (oldGrade == null) {
                    oldGrade = new Grade();
                    oldGrade.setId(studentGrade.getGradeId());
                }
            }

            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());
            //使用本学期使用课时
            Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSchoolId(), courseSchedulingDetailInfo.getSubjectsId(), studentId, courseSchedulingDetailInfo.getLessonType());
            //状态不为消课的,并且为精品课
            if (!courseType.equals(5) && courseSchedulingDetailInfo.getLessonType().equals(1)) {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter());
                //超过15次课，是否继续扣课时
                if (quarter.getIsDeductHouse().equals(0)) {
                    if (useCount >= 45) {
                        //请假，请假的不添加数据，直接返回
                        //大于45课时，请假的不添加记录
                        return null;
                    }
                }
            }
            Student student = studentMapper.selectById(studentId);

            recordCourse = new RecordCourse();
            recordCourse.setId(idWorker.nextId());
            recordCourse.setLessonType(courseSchedulingDetailInfo.getLessonType());
            recordCourse.setLessonNum(courseSchedulingDetailInfo.getLessonNum());//课次
            recordCourse.setSchedulingDetailId(schedulingDetailId);
            recordCourse.setStudentId(studentId);
            recordCourse.setStudentName(student.getName());
            recordCourse.setStatus(status);
            recordCourse.setType(type);
            recordCourse.setCourseType(courseType);
            recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
            recordCourse.setSchoolName(courseSchedulingDetailInfo.getSchoolName());
            recordCourse.setGradeId(grade.getId());
            recordCourse.setGradeName(grade.getName());
            recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
            recordCourse.setTeacherName(courseSchedulingDetailInfo.getTeacherName());
            recordCourse.setOldGradeId(oldGrade.getId());
            recordCourse.setOldTeacherId(oldGrade.getTeacherId());
            recordCourse.setYearClassId(grade.getYearClassId().getKey());
            recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
            recordCourse.setClassRoomName(courseSchedulingDetailInfo.getClassRoomName());
            recordCourse.setCourseId(courseSchedulingDetailInfo.getCourseId());
            recordCourse.setCourseName(courseSchedulingDetailInfo.getCourseName());
            recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
            recordCourse.setSubjectsName(courseSchedulingDetailInfo.getSubjectsName());
            recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
            recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
            recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
            recordCourse.setStartDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeStart() + ":00"));
            recordCourse.setEndDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeEnd() + ":00"));
            recordCourse.setYearAndQuarter(yearAndQuarter);
            recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
            recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
            recordCourse.setUseLeaveNum(1);//请假的这里设置为使用一次
            if (courseType.equals(4)) {
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(courseSchedulingDetailInfo.getPid());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                    }
                } catch (Exception e) {
                }
            }

            //获取精品课最后一次排课
            StudentGrade studentGradeLast = iStudentGradeService.getLastOne(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), 1);
            if (studentGradeLast != null) {
                recordCourse.setOldGradeId(studentGradeLast.getGradeId());
                Grade gradeLast = iGradeService.getById(studentGradeLast.getGradeId());
                if (gradeLast != null) {
                    Staff staffOld = iStaffService.getById(gradeLast.getTeacherId());
                    recordCourse.setOldTeacherId(gradeLast.getTeacherId());
                    recordCourse.setYearClassId(gradeLast.getYearClassId().getKey());
                    recordCourse.setGradeId(gradeLast.getId());
                    recordCourse.setGradeName(gradeLast.getName());
                    recordCourse.setTeacherId(gradeLast.getTeacherId());
                    recordCourse.setTeacherName(staffOld.getName());
                    recordCourse.setOldGradeId(gradeLast.getId());
                }
            }
            recordCourseMapper.insert(recordCourse);
            return recordCourse;
        } catch (Exception e) {
            System.out.println("recordActionError:" + e.getMessage());
            return null;
        }
    }

}
